/* eslint-disable react-native/no-inline-styles */
import React, { Component } from 'react';
import {
  View,
  StyleSheet,
  Text,
  Image,
  TouchableOpacity,
  ActivityIndicator,
  FlatList,
  Modal,
  ImageBackground
} from 'react-native';
import styled from 'styled-components';
import { Actions } from 'react-native-router-flux';
// import DatePicker from 'react-native-datepicker';
let pageNo = 1; //当前第几页
let totalPage = 5; //总的页数
let itemNo = 0; //item的个数
const REQUEST_URL =
  'https://api.github.com/search/repositories?q=javascript&sort=stars&page=';
export default class informIdx extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: '通知通告',
      imgUrl: require('../../../assets/work/sportsRankings/backtrack.png'),
      isLoading: true,
      //网络请求状态
      error: false,
      errorInfo: '',
      dataArray: [],
      showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      isRefreshing: false, //下拉控制
      handleStatus: false,
      handleX: 0,
      handleY: 0
    };
  }
  //网络请求——获取第pageNo页数据
  fetchData(pageNo) {
    //这个是js的访问网络的方法
    fetch(REQUEST_URL + pageNo)
      .then(response => response.json())
      .then(responseData => {
        let data = responseData.items;
        let dataBlob = [];
        let i = itemNo;

        data.map(function(item) {
          dataBlob.push({
            key: i,
            value: item
          });
          i++;
        });
        itemNo = i;
        console.log('itemNo:' + itemNo);
        let foot = 0;
        if (pageNo >= totalPage) {
          foot = 1; //listView底部显示没有更多数据了
        }

        this.setState({
          //复制数据源
          dataArray: this.state.dataArray.concat(dataBlob),
          isLoading: false,
          showFoot: foot,
          isRefreshing: false
        });
        data = null;
        dataBlob = null;
      })
      .catch(error => {
        this.setState({
          error: true,
          errorInfo: error
        });
      })
      .done();
  }

  componentDidMount() {
    this.fetchData(pageNo);
  }

  //加载等待页
  renderLoadingView() {
    return (
      <View style={styles.container}>
        <ActivityIndicator animating={true} color="red" size="large" />
      </View>
    );
  }

  //加载失败view
  renderErrorView() {
    return (
      <View style={styles.container}>
        <Text>Fail</Text>
      </View>
    );
  }

  //返回itemView
  _renderItemView({ item }) {
    return (
      <View style={{ paddingLeft: 20, paddingRight: 20, paddingTop: 30 }}>
        <View
          style={{
            padding: 15,
            backgroundColor: '#fff',
            width: '100%',
            borderRadius: 5
          }}>
          <Text style={{ color: '#333', fontSize: 14 }}>{item.value.name}</Text>
          <Text style={{ color: '#999', fontSize: 12 }}>
            description: {item.value.description}
          </Text>
          <Text
            style={{
              position: 'absolute',
              top: -25,
              width: '100%',
              textAlign: 'center',
              color: '#999',
              fontSize: 12
            }}>
            2019-06-28 15:30
          </Text>
        </View>
      </View>
    );
  }
  renderData() {
    return (
      <FlatList
        data={this.state.dataArray}
        renderItem={this._renderItemView}
        ListFooterComponent={this._renderFooter.bind(this)}
        onEndReached={this._onEndReached.bind(this)}
        onEndReachedThreshold={1.5}
        ItemSeparatorComponent={this._separator}
      />
    );
  }
  render() {
    //第一次加载等待的view
    if (this.state.isLoading && !this.state.error) {
      return this.renderLoadingView();
    } else if (this.state.error) {
      //请求失败view
      return this.renderErrorView();
    }
    return (
      <View style={{ flex: 1 }}>
        <View style={styles.header}>
          <TouchableOpacity onPress={() => Actions.pop()}>
            <View>
              <Image
                source={this.state.imgUrl}
                style={{ width: 25.67, height: 22.33, marginBottom: 5 }}
              />
            </View>
          </TouchableOpacity>
          <View
            style={{
              borderBottomColor: '#EDEDED',
              borderBottomWidth: 1,
              borderBottomStyle: 'dashed',
              flexDirection: 'row',
              justifyContent: 'space-between',
              position: 'relative',
              bottom: 0
            }}>
            <Text style={{ fontSize: 30, fontWeight: 'bold' }}>
              {this.state.title}
            </Text>
            <View>
              <TouchableOpacity
                onPress={({ nativeEvent: e }) => {
                  console.log('show : ');
                  this.setState({ handleStatus: true });
                }}>
                <Image
                  onLayout={this._onLayout}
                  source={require('../../../assets/work/inform/moreHandle.png')}
                  style={{
                    width: 16.75,
                    height: 3.5,
                    marginTop: 18,
                    position: 'relative'
                  }}
                />
              </TouchableOpacity>
            </View>
            <Modal
              animationType="fade" // 指定了 modal 的动画类型。类型：slide 从底部滑入滑出|fade 淡入淡出|none 没有动画
              transparent={true} // 背景是否透明，默认为白色，当为true时表示背景为透明。
              visible={this.state.handleStatus} // 是否显示 modal 窗口
              onRequestClose={() => {
                // this._closeModalWin();
                console.log('close Callback');
              }} // 回调会在用户按下 Android 设备上的后退按键或是 Apple TV 上的菜单键时触发。请务必注意本属性在 Android 平台上为必填，且会在 modal 处于开启状态时阻止BackHandler事件
              onShow={() => {
                console.log('modal窗口显示了');
                // this.setState({ curIndex: '' });
              }} // 回调函数会在 modal 显示时调用
            >
              <TouchableOpacity
                style={{ flex: 1 }}
                onPress={() => {
                  this.setState({ handleStatus: false });
                }}>
                <View style={{ position: 'absolute', top: 70, right: 15 }}>
                  <ImageBackground
                    style={{
                      // flex: 1,
                      width: 53.25,
                      height: 50.25,
                      display: this.state.handleStatus ? 'flex' : 'none'
                    }}
                    source={require('../../../assets/work/inform/bg_handle.png')}>
                    <View style={{ width: 53.25, height: 50.25 }}>
                      <Text
                        onPress={() => {
                          console.log('asdasd');
                          this.setState({ handleStatus: false });
                          Actions.infoAction();
                        }}
                        style={{
                          color: '#fff',
                          fontSize: 9,
                          textAlign: 'center',
                          lineHeight: 25
                        }}>
                        发起
                      </Text>
                      <Text
                        style={{
                          color: '#fff',
                          fontSize: 9,
                          textAlign: 'center',
                          lineHeight: 25
                        }}>
                        审批
                      </Text>
                    </View>
                  </ImageBackground>
                </View>
              </TouchableOpacity>
            </Modal>
            {/*  */}
          </View>
        </View>
        {this.renderData()}
      </View>
    );
  }
  _onLayout = e => {
    const { x, y, width, height } = e.nativeEvent.layout;
    this.setState({ handleX: x, handleY: y });
  };
  _separator() {
    return null;
  }
  _renderFooter() {
    if (this.state.showFoot === 1) {
      return (
        <View
          style={{
            height: 30,
            alignItems: 'center',
            justifyContent: 'flex-start'
          }}>
          <Text
            style={{
              color: '#999999',
              fontSize: 14,
              marginTop: 5,
              marginBottom: 5
            }}>
            没有更多数据了
          </Text>
        </View>
      );
    } else if (this.state.showFoot === 2) {
      return (
        <View style={styles.footer}>
          <ActivityIndicator />
          <Text>正在加载更多数据...</Text>
        </View>
      );
    } else if (this.state.showFoot === 0) {
      return (
        <View style={styles.footer}>
          <Text />
        </View>
      );
    }
  }

  _onEndReached() {
    //如果是正在加载中或没有更多数据了，则返回
    if (this.state.showFoot !== 0) {
      return;
    }
    //如果当前页大于或等于总页数，那就是到最后一页了，返回
    if (pageNo !== 1 && pageNo >= totalPage) {
      return;
    } else {
      pageNo++;
    }
    //底部显示正在加载更多数据
    this.setState({ showFoot: 2 });
    //获取数据
    this.fetchData(pageNo);
  }
}

const styles = StyleSheet.create({
  header: {
    width: '100%',
    height: 98,
    backgroundColor: '#FFFFFF',
    padding: 19.33
  },
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF'
  },
  title: {
    fontSize: 15,
    color: 'blue'
  },
  footer: {
    flexDirection: 'row',
    height: 24,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 10
  },
  content: {
    fontSize: 15,
    color: 'black'
  },
  modalLayer: {
    backgroundColor: 'rgba(0, 0, 0, 0.01)'
  }
});
const OnTouchableOpacity = styled.TouchableOpacity`
  flex-direction: row;
  align-items: center;
  justify-content: center;
`;
// AppRegistry.registerComponent('ECharts', () => ECharts);
